<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<script src="TreeNode.js"></script>
<script>
  let root = new TreeNode(1, null, null);
  let tree_2 = new TreeNode(2, null, null);
  let tree_3 = new TreeNode(3, null, null);
  let tree_4 = new TreeNode(4, null, null);
  let tree_5 = new TreeNode(5, null, null);
  let tree_6 = new TreeNode(6, null, null);
  let tree_7 = new TreeNode(7, null, null);

  root.left = tree_2;
  root.right = tree_3;
  tree_2.left = tree_4;
  tree_2.right = tree_5;
  tree_3.left = tree_6;
  tree_3.right = tree_7;

  console.log(root);

  /* 深度优先遍历 */
  // 前序遍历
  // const preOrder = (root) => {
  //   if (!root) return;
  //   console.log(root.val);
  //   preOrder(root.left);
  //   preOrder(root.right);
  // };
  // preOrder(root);
  // 数组
  const preOrder = (root) => {
    if (!root) return;
    //栈
    const stack = [root];
    while (stack.length) {
      const n = stack.pop();
      console.log(n.val);
      if (n.right) {
        stack.push(n.right);
      }
      if (n.left) {
        stack.push(n.left);
      }
    }
  };
  // preOrder(root);


  const inOrder = (root) => {
    if (!root) return;
    inOrder(root.left);
    console.log(root.val);
    inOrder(root.right);
  };
  // inOrder(root);

  /* 广度优先遍历 */
  const levelOrder = root => {
    if (!root) return null;
    // 创建一个队列
    const queue = [root];
    let res = [];
    while (queue.length) {
      // 取出当前的节点
      let n = queue.shift();
      res.push(n.val);
      // 把n.left 和 n的right 放到队列
      n.left && queue.push(n.left);
      n.right && queue.push(n.right);
    }
    return res;
  };

  let res = levelOrder(root);
  console.log(res);

</script>
</body>
</html>
